import java.util.*;

public class Solution347 {

    public static void main(String[] args) {
        int[] nums = new int[]{1, 2};
        int[] ints = topKFrequent(nums, 2);
        System.out.println(Arrays.toString(ints));
    }


    public static int[] topKFrequent(int[] nums, int k) {
        //先构建次数数组
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }
        //存结果
        int[] result = new int[k];
        //利用堆排序
        PriorityQueue<Integer> p = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                //比较元素出现次数，思路卡这里
                return map.get(o2) -  map.get(o1);
            }
        });
        for (Map.Entry<Integer, Integer> m : map.entrySet()) {
            Integer key = m.getKey();
            Integer value = m.getValue();
            p.add(key);
        }

        for (int i = 0; i < result.length; i++) {
            result[i] = p.poll();
        }
        return result;
    }
}
